package com.gdzl_hadoop.service.Impl;

import ch.ethz.ssh2.StreamGobbler;
import com.gdzl_hadoop.common.Const;
import com.gdzl_hadoop.common.ServerResponse;
import com.gdzl_hadoop.dao.*;
import com.gdzl_hadoop.pojo.*;
import com.gdzl_hadoop.service.IDataHandleService;
import com.gdzl_hadoop.util.XzqMenuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;

/**
 * Created by 1032019725 on 2017/10/18.
 */
@Service("iDataHandleService")
public class DataHandleServiceImpl implements IDataHandleService {

    @Autowired
    private YsglMapper ysglMapper;
    @Autowired
    private Hlxfx_szMapper hlxfx_szMapper;
    @Autowired
    private Hlxfx_zfMapper hlxfx_zfMapper;

    @Autowired
    private RfMapper rfMapper;
    @Autowired
    private Rf_cmMapper rf_cmMapper;

    @Autowired
    private XzqMapper xzqMapper;
    @Autowired
    private FileRecordMapper fileRecordMapper;

    //region RandomForest

    /**
     * 把随机森林结果存入数据库
     *
     * @param res  结果
     * @param guid
     * @return
     */
    @Override
    public int InsertRandomForestData(String res, String guid) {
        String line, x, y, Kappa, Accuracy, Reliability, Reliability_sd;
        int total = 0, start = 0, last = 0;
        List<String> temp = new ArrayList<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(res.getBytes(Charset.forName("utf-8"))), Charset.forName("utf-8")));
        try {
            while ((line = br.readLine()) != null) {
                total++;
                temp.add(line);

                if (line.startsWith("Confusion Matrix")) {
                    String judge = br.readLine();
                    if (judge.startsWith("-") & judge.endsWith("-")) {
                        temp.add(judge);
                        total++;
                        start = total + 2;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        last = total - 9;

        //完整数据
        String[] lines = new String[total];
        lines = (String[]) temp.toArray(new String[temp.size()]);
        //找到四个指标的对应行
        Reliability_sd = lines[total - 2];
        Reliability = lines[total - 3];
        Accuracy = lines[total - 4];
        Kappa = lines[total - 5];
        //获取四个指标
        String Kappa_Num = Kappa.substring(Kappa.lastIndexOf(" ") + 1);
        String Accuracy_Num = Accuracy.substring(Accuracy.lastIndexOf(" ") + 1);
        String Reliability_sd_Num = Reliability_sd.substring(Reliability_sd.lastIndexOf(" ") + 1);
        String Reliability_Num = Reliability.substring(Reliability.lastIndexOf(" ") + 1);

        int rf_Lines = 0;//rf表成功插入的行数
        Rf rf = new Rf();
        rf.setGuid(guid);
        rf.setKappa(Kappa_Num);
        rf.setAccuracy(Accuracy_Num);
        rf.setReliability(Reliability_Num);
        rf.setReliabilitySd(Reliability_sd_Num);
        rf_Lines = rfMapper.insert(rf);

        int rf_cmLines = 0;//rf_cm表成功插入
        //获取标签
        List<String> labels = new ArrayList<>();
        for (int i = start; i <= last; i++) {
            labels.add(lines[i - 1].substring(lines[i - 1].lastIndexOf("=") + 2));
        }

        //获取混淆矩阵
        String[] linesDatas = new String[last - start + 1];
        for (int i = 0; i < last - start + 1; i++) {
            linesDatas[i] = lines[start - 1 + i].substring(0, lines[start + 1].lastIndexOf("|") - 1);
        }
        //切割存储矩阵每个值
        String[][] data = new String[labels.size()][labels.size()];

        for (int row = 0; row < labels.size(); row++) {
            data[row] = linesDatas[row].split("\t");

            for (int col = 0; col < labels.size(); col++) {
                String tem = data[row][col].trim();
                data[row][col] = tem;
                rf_cmLines = CMDataToDb(labels.get(row), labels.get(col), data[row][col], rf.getId());

            }
        }

        return (rf_Lines > 0 & rf_cmLines > 0) ? 1 : -1;
    }

    /**
     * 把混淆矩阵每一行的数据插入数据库
     *
     * @param x,y,data
     */
    private int CMDataToDb(String x, String y, String data, Long id) {
        int j = 0;
        Rf_cm rf_cm = new Rf_cm();
        rf_cm.setVaule(Integer.valueOf(data));
        rf_cm.setX(x);
        rf_cm.setY(y);
        rf_cm.setRfid(id);
        j = rf_cmMapper.insert(rf_cm);
        return j;

    }

    /**
     * 获取随机森林数据、矩阵数据
     *
     * @param guid
     * @return
     */
    @Override
    public ServerResponse<ForestRandom> getRFData(String guid) {
        ForestRandom forestRandom = new ForestRandom();
        Rf rf = rfMapper.selectByGuid(guid);
        forestRandom.setAccuary(rf.getAccuracy());
        forestRandom.setKappa(rf.getKappa());
        forestRandom.setReliability(rf.getReliability());
        forestRandom.setReliability_sd(rf.getReliabilitySd());

        List<Rf_cm> dataList = rf_cmMapper.selectByRfId(String.valueOf(rf.getId()));
        int label_num = (int) Math.sqrt(dataList.size());
        List<String> xList = new ArrayList<>();
        List<String> yList = new ArrayList<>();
        String[][] values = new String[label_num + 1][label_num + 1];
        for (Rf_cm rfcm : dataList) {
            String x = rfcm.getX();
            String y = rfcm.getY();
            if (!xList.contains(x))
                xList.add(x);
            if (!yList.contains(y))
                yList.add(y);

            int xIndex = xList.indexOf(x) + 1;
            int yIndex = yList.indexOf(y) + 1;
            values[xIndex][yIndex] = rfcm.getVaule().toString();
        }

        for (int i = 0; i < xList.size(); i++) {
            values[i + 1][0] = xList.get(i);
        }
        for (int i = 0; i < yList.size(); i++) {
            values[0][i + 1] = yList.get(i);
        }

        /*String[] x=new String[dataList.size()];
        String[] y=new String[dataList.size()];
        String[][] values=new String[label_num + 1][label_num + 1];
        int i=0,j=0,z=0;//i行，z列
        for(Rf_cm temp:dataList){
            x[j]=temp.getX();
            y[j++]=temp.getY();
            if(values[i][label_num-1]==null) {//判断是否到达最后一行
                values[i][z++] = String.valueOf(temp.getVaule());
            }else{
                i++;
                z=0;
                values[i][z++] = String.valueOf(temp.getVaule());
            }
        }*/

        forestRandom.setValues(values);
        /*forestRandom.setRowNames(x);
        forestRandom.setColumNames(y);*/
//
//        for(String o:x){
//            System.out.print(o+" ");
//        }
//        for(String o:y){
//            System.out.print(o+" ");
//        }
//        for(String[] o:values){
//            for(String l:o)
//            System.out.println(l+" ");
//        }
        return ServerResponse.createBySuccess(forestRandom);
    }

    //endregion

    //region FPGoperation

    //    private static final String YXTCHD = "YXTCHD";//有效土层厚度(0,30],(30-60],(60-100],(100,)
//    private static final String BCTRZD = "BCTRZD";//表层土壤质地
//    private static final String PMGX = "PMGX";//剖面构型
//    private static final String TRYJZHL = "TRYJZHL";//土壤有机质含量(0,6],(6,10],(10,20],(20,30]，（30，】
//    private static final String TRSJD = "TRSJD";//土壤酸碱度<0,4.5],(4.5,  5],(5.0,5.5],(5.5,6.0],(6.0-7.9],(7.9,8.5],(8.5,9], (9,]
//    private static final String PSTJ = "PSTJ";//排水条件
//    private static final String DXPD = "DXPD";//地形坡度
//    private static final String GGBZL = "GGBZL";//灌溉保证率
//    private static final String TMPD = "TMPD";//田面坡度
//    private static final String DXSW = "DXSW";//地下水位(0,30]、(30,60]、(60,)

    @Override
    public Map<String, List<String>> getFpgRule(double confidenceNum, String result, String year, String xzqdm) {
        BufferedReader res = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(result.getBytes(Charset.forName("utf-8"))), Charset.forName("utf-8")));
        // BufferedReader list = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(fList.getBytes(Charset.forName("utf-8"))), Charset.forName("utf-8")));
        String lineRes;
        Map<String, List<String>> rules = new HashMap<>();
        //   StringBuffer rules = new StringBuffer();
        for (int i = 0; i < 12; i++) {
            try {
                res.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            while ((lineRes = res.readLine()) != null) {

                if (!lineRes.startsWith("Key:")) {
                    continue;
                } else {
                    List<String> currentLineRuleDetail = new ArrayList<>();//每个key的规则列表
                    System.out.println(lineRes);
                    //检查第一个项集是否是单项集
                    String valueOne = lineRes.substring(lineRes.indexOf('[') + 1, lineRes.indexOf(']')).trim();//第一个项集
                    String keyF = lineRes.split("Key: |: Value: ")[1].trim();//key

                    //分割key和value
                    String[] str1 = lineRes.split("Key: |: Value: ");
                    String value = str1[2].trim();//全部value
                    //去除value后面的值的首尾括号
                    String valueTrim = value.substring(2, value.length() - 1);
                    //替换value后面的数据集分割符
                    valueTrim = valueTrim.replace("), ([", "&");
                    valueTrim = valueTrim.replace("],", ",");
                    valueTrim = valueTrim.replaceAll(" ", "");
                    //分割出规则列表
                    String[] vals = valueTrim.split("&");//[0]为单项集
                    String keyNum = vals[0].substring(vals[0].indexOf(',') + 1);//key支持度
                    int isSingle = 0;
                    if (valueOne.equals(keyF)) { //如果第一个是单项集=key,跳过不加入
                        isSingle++;
                    }
                    for (int i = isSingle; i < vals.length; i++) {     //  遍历当前行所有项集
                        if (vals.length == 1)
                            break;

                        //  System.out.println(i+"+"+vals[i]);
                        String valueNum = vals[i].substring(vals[i].lastIndexOf(',') + 1);//当前项集支持度
                        BigDecimal keyBigDecimal = new BigDecimal(keyNum);
                        BigDecimal valueBigDecimal = new BigDecimal(valueNum);
                        //四舍五入，保留四位，对比置信概率
                        if (valueBigDecimal.divide(keyBigDecimal, 4, BigDecimal.ROUND_HALF_UP).compareTo(new BigDecimal(Double.toString(confidenceNum))) > 0) {
                            //规则入库
                            String valuesWithoutSup = vals[i].substring(0, vals[i].lastIndexOf(','));//当前项集（去支持度）
                            String[] eachValue = valuesWithoutSup.split(",");//当前项集 TMPD:G1,DXPD:G1,TRYJZHL:more分割

                            for (int j = 0; j < eachValue.length; j++) {//遍历：TMPD:G1,DXPD:G1,TRYJZHL:more,替换数据
                                String each_fact = eachValue[j].split(":")[0];
                                String temp = eachValue[j].split(":")[1];
                                if (each_fact.equals("YXTCHD")) {
                                    switch (temp) {
                                        case "30":
                                            temp = "(0,30]";
                                            break;
                                        case "60":
                                            temp = "(30,60]";
                                            break;
                                        case "100":
                                            temp = "(60,100]";
                                            break;
                                        case "more":
                                            temp = "(100,omega)";
                                            break;
                                    }
                                } else if (each_fact.equals("TRYJZHL")) {
                                    switch (temp) {
                                        case "6":
                                            temp = "(0,6]";
                                            break;
                                        case "10":
                                            temp = "(6,10]";
                                            break;
                                        case "20":
                                            temp = "(10,20]";
                                            break;
                                        case "30":
                                            temp = "(20,30]";
                                            break;
                                        case "more":
                                            temp = "(30,omega)";
                                            break;
                                    }
                                } else if (each_fact.equals("TRSJD")) {
                                    switch (temp) {
                                        case "4.5":
                                            temp = "(0,4.5]";
                                            break;
                                        case "5":
                                            temp = "(4.5,5]";
                                            break;
                                        case "5.5":
                                            temp = "(5,5.5]";
                                            break;
                                        case "6":
                                            temp = "(5.5,6]";
                                            break;
                                        case "7.9":
                                            temp = "(6,7.9]";
                                            break;
                                        case "8.5":
                                            temp = "(7.9,8.5]";
                                            break;
                                        case "9":
                                            temp = "(8.5,omega)";
                                            break;
                                    }
                                } else if (each_fact.equals("DXSW")) {
                                    switch (temp) {
                                        case "30":
                                            temp = "(0,30]";
                                            break;
                                        case "60":
                                            temp = "(30,60]";
                                            break;
                                        case "more":
                                            temp = "(60,omega)";
                                            break;
                                    }
                                }
                                eachValue[j] = each_fact + "," + temp;
                            }//end替换

                            StringBuffer add = new StringBuffer();
                            for (String tem : eachValue) {

                                add.append("<" + tem + ">,");
                            }
                            add.deleteCharAt(add.length() - 1);
                            currentLineRuleDetail.add(add.toString());//加入当前项集规则
                        }
                        //end遍历当前行的每一个项集
                        //end单项集
                    }
                    if (currentLineRuleDetail.size() > 0)
                        rules.put(keyF, currentLineRuleDetail);//key: rules的格式

                }//end行遍历
            }//endwhile
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rules;
    }

    /***
     *把FPG算法的结果计算完成后的一行数据进行处理，处理成String,List<Map<String,String>>格式
     * @param lineData
     * @return
     */
    private void FPG_DataToYsglTmp(String lineData, YsglTmp ysglTmp) {
        Map<String, String> valMap = new HashMap<String, String>();
        //定义存储结构，用于存每一行的记录
        //Map<String,List<Map<String,String>> > valMap = new HashMap<String,List<Map<String,String>> >();
        //定义存储结构，用于存value后面的数据
        List<String> list = new ArrayList<String>();
        //分割key和value
        String[] str1 = lineData.split("Key: |: Value: ");
        //去除空格
        String key = str1[1].trim();
        String value = str1[2].trim();
        //去除value后面的值的首尾括号
        String valueTrim = value.substring(2, value.length() - 1);
        //替换value后面的数据集分割符
        valueTrim = valueTrim.replace("), ([", "&");
        valueTrim = valueTrim.replace("],", ",");
        //分割出数据
        String[] vals = valueTrim.split("&");
        //分割成大集合 如DBYSLTD:1, DXPD:G1, GGBZL:1, GGSY:1, PSTJ:1, YXTCHD:100, YZHCD:1, ZACJDBSD:90, BCTRZD:MR,201   存入vals中
        //和key配合，生成map1(key,map2(vlaue,count))
        //valMap.put(key, value)
        ysglTmp.setYS1(key);
        if (key == "PMGX:A1") {
            int mm = 0;
        }
        ysglTmp.setYS_name(key.split(":")[0]);
        ysglTmp.setYS_value(key.split(":")[1]);

        for (int i = 0; i < vals.length; i++) {
            //把大集合分割成 DBYSLTD:1 这种键值对放到mapvals
            String[] mapvals = vals[i].split(",");
            Map<String, String> valueMap = new HashMap<String, String>();
            int cnt = mapvals.length;
            //如果不大于1，这行数据不是我们需要处理的格式的数据
            if (cnt > 1) {
                for (int j = 0; j < mapvals.length - 2; j++) {
                    //判断key是否已经存在了，如果存在了，就把数字累加
                    //判断key是否已经存在了，如果存在了，就把数字累加
//                    if(valMap.containsKey(mapvals[j])){
//                        int dvalue =Integer.parseInt(valMap.get(mapvals[j])) +  Integer.parseInt(mapvals[cnt-1]);
//                        valMap.put(mapvals[j], Integer.toString(dvalue));
//                    }
//                    else{
//                        valMap.put(mapvals[j], mapvals[cnt-1]);
//                    }
                    if (!valMap.containsKey(mapvals[j])) {
                        valMap.put(mapvals[j], mapvals[cnt - 1]);
                    }
                }
            }
        }
        ysglTmp.setValMap(valMap);

    }

    ;

    /***
     * 把一行数据插入db
     * @param ysglTmp
     */
    public void YsglTmpToDb(YsglTmp ysglTmp, String guid) {

        Map<String, String> valMap = ysglTmp.getValMap();
        if (valMap.size() > 0) {
            for (Map.Entry<String, String> item : valMap.entrySet()) {
                Ysgl ysgl = new Ysgl();
                ysgl.setYs1(ysglTmp.getYS1());
                ysgl.setYs1Name(ysglTmp.getYS_name());
                ysgl.setYs1Value(ysglTmp.getYS_value());
                String key = item.getKey();
                ysgl.setYs2(key);
                ysgl.setYs2Name(key.split(":")[0]);
                ysgl.setYs2Value(key.split(":")[1]);
                ysgl.setDisplaytimes(Long.parseLong(item.getValue()));
                ysgl.setGuid(guid);

                //判断数据库是否有这两种因素的数据
//                int checkYSExist = checkExist(ysgl);
//                switch (checkYSExist){
//                    case -1:
//
//                        break;
//                    case 0:
//
//                        break;
//                    case 1:
//
//                        break;
//                    default:
//                        break;
//                }
                ysglMapper.insert(ysgl);
                //插入之前先判断是否在数据库存在有数据，有的话就更新数据，没有就插入
                String ys1 = ysglTmp.getYS1();
                String ys2 = key;
                ysgl = ysglMapper.checkExist(ys2, ys1, guid);
                if (ysgl == null) {
                    //插入新数据
                    ysgl = new Ysgl();
                    ysgl.setYs1(key);
                    ysgl.setYs1Name(key.split(":")[0]);
                    ysgl.setYs1Value(key.split(":")[1]);
                    ysgl.setYs2(ysglTmp.getYS1());
                    ysgl.setYs2Name(ysglTmp.getYS_name());
                    ysgl.setYs2Value(ysglTmp.getYS_value());
                    ysgl.setDisplaytimes(Long.parseLong(item.getValue()));
                    ysgl.setGuid(guid);
                    ysglMapper.insert(ysgl);
                } else {
                    //更新，取较大的
                    ysgl.setDisplaytimes(Long.parseLong(item.getValue()) > ysgl.getDisplaytimes() ? Long.parseLong(item.getValue()) : ysgl.getDisplaytimes());
                    ysglMapper.updateByPrimaryKey(ysgl);
                }
            }
        }
    }

    private int checkExist(Ysgl ysgl) {
        //用于记录数据在数据库中的情况
        //0为数据库中无这两个YS的记录，-1为YS1 YS2在数据库中有相反记录，1为有记录且顺序一致,-2为出错
        int resullt = -2;
        int YSRank1 = ysglMapper.checkYSExist(ysgl.getYs1Name(), ysgl.getYs2Name());
        int YSRank2 = ysglMapper.checkYSExist(ysgl.getYs2Name(), ysgl.getYs1Name());

        if (YSRank1 > 0 && YSRank2 == 0) {
            //该顺序有数据，以后的数据都按这个顺序来
            resullt = 1;
        } else if (YSRank1 == 0 && YSRank2 > 0) {
            //该顺序的逆序有数据，以后的数据都按这个顺序来
            resullt = -1;
        } else if (YSRank1 == 0 && YSRank2 == 0) {
            //无这两种YS下的数据
            resullt = 0;
        }
        return resullt;
    }

    /***
     * is为FPG的计算结果，把结果以文件流的形式读出来
     * @param is
     * @return
     */
    @Override
    public int InsertFPGData(InputStream is, String guid) {

        //删除db数据
        int delcount = ysglMapper.deleteAll();
        //定义存储结构，用于存每一行的记录
        Map<String, List<Map<String, String>>> valMap = new HashMap<String, List<Map<String, String>>>();
        //监测插入的数据行数
        int count = 0;
        try {

            java.io.InputStream stdout = new StreamGobbler(is);
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String lineData = br.readLine();
                if (lineData != null) {
                    count = lineToDb(lineData, count, guid);
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return count;
    }

    public int InsertFPGData(String res, String guid) {

        //删除db数据
        //int delcount = ysglMapper.deleteAll();
        ysglMapper.deleteByGuid(guid);
        //定义存储结构，用于存每一行的记录
        //Map<String,List<Map<String,String>> > valMap = new HashMap<String,List<Map<String,String>> >();
        //监测插入的数据行数
        int count = 0;
        String[] allData = res.split("\n");
        for (int i = 0; i < allData.length; i++) {
            String lineData = allData[i];
            count = lineToDb(lineData, count, guid);
        }
        return count;
    }

    /***
     * 根据两个因素生成关联信息二维表
     * @param YS1
     * @param YS2
     * @return
     */
    public ServerResponse<String[][]> getYsData(String YS1, String YS2, String guid) {
        List<Ysgl> ysglList = ysglMapper.selectYsglByName(YS1, YS2, guid);
        HashSet<String> ys1_Values = new HashSet<String>();
        HashSet<String> ys2_Values = new HashSet<String>();
        //遍历list 把两个因素的值加入两个哈希集合
        for (Ysgl item : ysglList) {
            String ys1Val = item.getYs1Value();
            String ys2Val = item.getYs2Value();
            if (!ys1_Values.contains(ys1Val)) {
                ys1_Values.add(ys1Val);
            }
            if (!ys2_Values.contains(ys2Val)) {
                ys2_Values.add(ys2Val);
            }
        }
        int i = 0;
        int j = 0;
        String[][] result = new String[ys1_Values.size() + 1][ys2_Values.size() + 1];
        for (String val_1 : ys1_Values) {
            result[i + 1][0] = val_1;
            j = 0;
            for (String val_2 : ys2_Values) {
                result[0][j + 1] = val_2;
                for (Ysgl item : ysglList) {
                    if (item.getYs1Value().equals(val_1) && item.getYs2Value().equals(val_2)) {
                        //查询到目标行，写入出现次数
                        result[i + 1][j + 1] = item.getDisplaytimes().toString();
                        break;
                    }
                }
                j++;
            }
            i++;
        }
        return ServerResponse.createBySuccess(result);
    }

    /***
     * 获取因素1的列表
     * @return
     */
    @Transactional
    public ServerResponse<List<String>> getYs1List(String guid) {
        List<String> list = ysglMapper.selectYS1_name(guid);
        if (list.size() > 0)
            return ServerResponse.createBySuccess(list);
        else
            return ServerResponse.createByErrorMessage("数据获取失败");
        //Hashtable;
        // ConcurrentHashMap
    }

    /***
     * 获取因素2的列表
     * @param YS1
     * @return
     */
    public ServerResponse<List<String>> getYs2List(String YS1, String guid) {
        List<String> list = ysglMapper.selectYS2_name(YS1, guid);
        if (list.size() > 0)
            return ServerResponse.createBySuccess(list);
        else
            return ServerResponse.createByErrorMessage("数据获取失败");
    }

    /**
     * 把一行数据插入数据库，一行中可能会带有多条数据
     *
     * @param lineData
     * @param count
     * @return
     */
    private int lineToDb(String lineData, int count, String guid) {
        if (lineData.startsWith("Key:")) {
            //FPG_DataToMap(lineData,valMap);
            YsglTmp ysglTmp = new YsglTmp();
            //装载数据
            FPG_DataToYsglTmp(lineData, ysglTmp);
            try {
                //插入数据库
                YsglTmpToDb(ysglTmp, guid);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            count++;
        }
        return count;
    }

    //endregion

    //region COMoperation

    /**
     * 根据因素名称获取合理性分析结果
     *
     * @param YS_name
     * @return
     */
    public ServerResponse<String[][]> getHlxfxResult(String YS_name, String guid) {

        //判断因素是字符还是数值型
        if (Const.Hlxfx_sz_map.containsKey(YS_name)) {
            //查找合理性分析数值型数据库
            List<Hlxfx_sz> szList = hlxfx_szMapper.getHlxfxSz(YS_name, guid);
            if (szList.size() > 0) {
                String[][] szArray = new String[szList.size() + 1][5];
                int i = 0;
                szArray[0][0] = "土种名称";
                szArray[0][1] = "方差";
                szArray[0][2] = "均值";
                szArray[0][3] = "最小值";
                szArray[i++][4] = "最大值";
                for (Hlxfx_sz item : szList) {
                    szArray[i][0] = item.getTzName();
                    szArray[i][1] = item.getStd().toString();
                    szArray[i][2] = item.getAvg().toString();
                    szArray[i][3] = item.getMin().toString();
                    szArray[i++][4] = item.getMax().toString();
                }
                return ServerResponse.createBySuccess(szArray);
            } else {
                return ServerResponse.createByErrorMessage("数据获取失败/无数据");
            }
        } else if (Const.Hlxfx_zf_map.containsKey(YS_name)) {
            ////查找合理性分析数值型数据库
            List<Hlxfx_zf> zfList = hlxfx_zfMapper.getHlxfxZf(YS_name, guid);
            if (zfList.size() > 0) {
                String[][] zfArray = new String[zfList.size() + 1][2];
                int i = 0;
                zfArray[0][0] = "土种名称";
                zfArray[i++][1] = "土种取值";
                for (Hlxfx_zf item : zfList) {
                    zfArray[i][0] = item.getTzName();
                    zfArray[i++][1] = item.getTzqz();
                }
                return ServerResponse.createBySuccess(zfArray);
            } else {
                return ServerResponse.createByErrorMessage("数据获取失败/无数据");
            }
        } else {
            return ServerResponse.createByErrorMessage("数据获取失败/无数据");
        }
    }

    /**
     * 通过输入流来吧数据插入数据库
     *
     * @param com_result
     * @return
     */
    public int InsertHlxfxData(String com_result, String guid) {
        //deleteHlxfxAll();
        deleteHlxfxByGuid(guid);

        String[] resultArray = com_result.split("\n");
        int datacount = 0;
        HashMap<String, Map<String, String>> zfMap = new HashMap<String, Map<String, String>>();
        try {
            char op = 'D';//默认为D
            String YSMC = "";//因素名称
            //List<String> YsmcList = new ArrayList<String>();
            //读取数据流
            for (int j = 0; j < resultArray.length; j++) {
                String lineData = resultArray[j];
//                if (j == 24) {
//                    int mm = 0;
//                }
                if (lineData == null || lineData.equals(""))
                    continue;
                //根据tab分割数据
                String[] dataArray = lineData.split("\t");
                //判断是否是字符型
                String dataArray_1 = dataArray[0].toString();
                //OP转换
                if (Const.Hlxfx_sz_map.containsKey(dataArray[0].toString())) {
                    op = 'S';
                    YSMC = dataArray[0];
                } else if (dataArray_1.equals("sstz")) {
                    op = 'Z';
                    YSMC = dataArray[1];
                }
                switch (op) {
                    case 'Z':
                        //字符型数据
                        if (dataArray_1.equals("sstz")) {
                            break;
                        }
                        if (zfMap.containsKey(YSMC)) {
                            Map<String, String> map = zfMap.get(YSMC);
                            if (map.containsKey(dataArray[0])) {
                                //存在土种
                                String tzVal = map.get(dataArray[0]);
                                tzVal = tzVal + "," + dataArray[1];
                                map.put(dataArray[0], tzVal);
                            } else {
                                map.put(dataArray[0], dataArray[1]);
                            }
                            zfMap.put(YSMC, map);

                        } else {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put(dataArray[0], dataArray[1]);
                            zfMap.put(YSMC, map);
                        }
                        break;
                    case 'S':
                        String res = dataArray[1].toString();
                        if (!res.toLowerCase().equals("std")) {
                            //数值型数据
                            Hlxfx_sz hlxfx_sz = loadHlxfxSz(dataArray, YSMC, guid);
                            datacount += hlxfx_szMapper.insert(hlxfx_sz);
                        }
                        break;
                    default:
                        break;
                }
            }

            for (String key : zfMap.keySet()) {
                Map<String, String> map = zfMap.get(key);
                for (String skey : map.keySet()) {
                    String value = map.get(skey);
                    Hlxfx_zf hlxfx_zf = new Hlxfx_zf();
                    hlxfx_zf.setYsName(key);
                    hlxfx_zf.setTzName(skey);
                    hlxfx_zf.setTzqz(value);
                    hlxfx_zf.setGuid(guid);
                    datacount += hlxfx_zfMapper.insert(hlxfx_zf);
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {

        }
        return datacount;
    }

    /**
     * 获取合理性分析因素
     *
     * @return
     */
    public ServerResponse<HashMap<String, String>> getHlxfxYsList(String guid) {
        List<String> ysList;
        HashMap<String, String> result = new HashMap<>();
        ysList = hlxfx_szMapper.getSzYSByGuid(guid);
        for (String ys : ysList) {
            result.put(ys, Const.Hlxfx_sz_map.get(ys));
        }
        ysList = hlxfx_zfMapper.getZfYSByGuid(guid);
        for (String ys : ysList) {
            result.put(ys, Const.Hlxfx_zf_map.get(ys));
        }
        if (ysList.size() > 0) {
            return ServerResponse.createBySuccess(result);
        } else {
            return ServerResponse.createByErrorMessage("获取因素失败！");
        }
    }

    /**
     * 合理性分析数值型装载
     */
    private Hlxfx_sz loadHlxfxSz(String[] dataArray, String YSMC, String guid) {
        Hlxfx_sz hlxfx_sz = new Hlxfx_sz();
        //装载
        hlxfx_sz.setYsName(YSMC);
        hlxfx_sz.setTzName(dataArray[0]);
        hlxfx_sz.setStd(Double.parseDouble(dataArray[1]));
        hlxfx_sz.setAvg(Double.parseDouble(dataArray[2]));
        hlxfx_sz.setMin(Double.parseDouble(dataArray[3]));
        hlxfx_sz.setMax(Double.parseDouble(dataArray[4]));
        hlxfx_sz.setGuid(guid);
        return hlxfx_sz;
    }

    /**
     * 删除数据库中合理性分析的数据
     */
    private void deleteHlxfxAll() {
        hlxfx_szMapper.deleteAll();
        hlxfx_zfMapper.deleteAll();
    }

    private void deleteHlxfxByGuid(String guid) {
        hlxfx_szMapper.deleteByGuid(guid);
        hlxfx_zfMapper.deleteByGuid(guid);
    }

    //endregion

    /**
     * 获得全省行政区树状结构(不包含年份，用于上传文件后选择)
     *
     * @return
     */
    public ServerResponse<List<Object>> getAllXqz() {
        XzqMenuUtil xzq = new XzqMenuUtil();

        List<Object> result = xzq.menuList(xzqMapper.findAllForTree());
        if (result.size() > 0) {
            return ServerResponse.createBySuccess(result);
        } else {
            return ServerResponse.createByErrorMessage("获取行政区失败！");
        }
    }

    /**
     * 文件上传提交
     *
     * @param filepath
     * @param xzqdm
     * @param year
     * @return
     */
    public int insertFileRecord(String fileName, String filepath, String xzqdm, String year) {
        FileRecord fileRecord = new FileRecord();
        fileRecord.setXzqdm(xzqdm);
        fileRecord.setPath(filepath);
        fileRecord.setYear(year);
        fileRecord.setFileName(fileName);

        //  idAndSuccess.put("fileId",fileRecord.getId());
        return fileRecordMapper.insert(fileRecord);
    }

    /**
     * 浏览用户上传过的数据,地图渲染
     *
     * @return
     */
    @Override
    public ServerResponse<Map<String, List<Object>>> getGeodata() {
        //每一级都要有一个下一级的数组，同级用对象Map存储数据，下一级用数组
        XzqMenuUtil xzqMenuUtil = new XzqMenuUtil();
        List<FileRecordVO> fileRecordVOS = fileRecordMapper.selectXzqdmGroupByYear();
        Map<String, List<Object>> yearForFiles = new HashMap<>();
        for (FileRecordVO ob : fileRecordVOS) {
            //regionDeal 每个年份的文件记录
            List<Xzq> temp = ob.getFileRecords();
            // Set<String> xzqdms = new HashSet<>();//保存拥有文件的行政区代码-集合（作标记）
            Map<String, List<String>> xzqdms = new HashMap<>();
            Set<Xzq> xzqMenu = new LinkedHashSet<>();//保存不重复的行政区对象（数据库记录，工具类用于构建行政区树）

            xzqMenu.add(new Xzq("44", "广东省", "-1"));//默认省肯定要有，如果遇到有省级文件再保存44代码
            for (Xzq xzq : temp) {//遍历当前年份的所有文件,每个xzq已经有xzqdm和xzqmc
                String each_xzqdm = xzq.getXzqdm().trim();
                xzqdms.put(each_xzqdm, fileRecordMapper.selectPathByXzqdm(each_xzqdm));//保存有文件的行政代码以便做标记-自动排重
                String parentid, level2, level3, level4 = null;

                if (each_xzqdm.length() == 2) {
                    continue;
                } else if (each_xzqdm.length() == 4) {//市
                    parentid = each_xzqdm.substring(0, 2);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                } else if (each_xzqdm.length() == 6) {//县
                    parentid = each_xzqdm.substring(0, 4);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                    //添加上级市
                    level2 = xzqMapper.selectXzqmcByXzqdm(parentid);

                    xzqMenu.add(new Xzq(parentid, level2, "44"));
                } else if (each_xzqdm.length() == 9) {//乡
                    parentid = each_xzqdm.substring(0, 6);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                    //添加上级市、县
                    level3 = xzqMapper.selectXzqmcByXzqdm(parentid);
                    level2 = xzqMapper.selectXzqmcByXzqdm(each_xzqdm.substring(0, 4));

                    xzqMenu.add(new Xzq(parentid, level3, each_xzqdm.substring(0, 4)));
                    xzqMenu.add(new Xzq(each_xzqdm.substring(0, 4), level2, "44"));
                } else if (each_xzqdm.length() == 12) {//村
                    parentid = each_xzqdm.substring(0, 9);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                    //添加上级市、县、乡
                    level4 = xzqMapper.selectXzqmcByXzqdm(parentid);
                    level3 = xzqMapper.selectXzqmcByXzqdm(each_xzqdm.substring(0, 6));
                    level2 = xzqMapper.selectXzqmcByXzqdm(each_xzqdm.substring(0, 4));

                    xzqMenu.add(new Xzq(parentid, level4, each_xzqdm.substring(0, 6)));
                    xzqMenu.add(new Xzq(each_xzqdm.substring(0, 6), level3, each_xzqdm.substring(0, 4)));
                    xzqMenu.add(new Xzq(each_xzqdm.substring(0, 4), level2, "44"));
                }
            }//end everyYearFileDeal

            List<Xzq> list = new LinkedList<>(xzqMenu);
            yearForFiles.put(ob.getYear(), xzqMenuUtil.menuList(list, xzqdms));
        }//endVO
        return ServerResponse.createBySuccess(yearForFiles);
    }

    /**
     * 浏览用户上传过的数据,地图渲染
     *
     * @return
     */
    @Override
    public ServerResponse<Map<String, List<Object>>> getGeodataByXzqdm(String xzqdm ) {
        //每一级都要有一个下一级的数组，同级用对象Map存储数据，下一级用数组
        XzqMenuUtil xzqMenuUtil = new XzqMenuUtil();
        List<FileRecordVO> fileRecordVOS = fileRecordMapper.selectXzpHasFileGroupByXzqdm(xzqdm);
        Map<String, List<Object>> yearForFiles = new HashMap<>();
        for (FileRecordVO ob : fileRecordVOS) {
            //regionDeal 每个年份的文件记录
            List<Xzq> temp = ob.getFileRecords();
            // Set<String> xzqdms = new HashSet<>();//保存拥有文件的行政区代码-集合（作标记）
            Map<String, List<String>> xzqdms = new HashMap<>();
            Set<Xzq> xzqMenu = new LinkedHashSet<>();//保存不重复的行政区对象（数据库记录，工具类用于构建行政区树）

            xzqMenu.add(new Xzq(xzqdm, xzqMapper.selectXzqmcByXzqdm(xzqdm), "-1"));//默认省肯定要有，如果遇到有省级文件再保存44代码
            for (Xzq xzq : temp) {//遍历当前年份的所有文件,每个xzq已经有xzqdm和xzqmc
                String each_xzqdm = xzq.getXzqdm().trim();
                xzqdms.put(each_xzqdm, fileRecordMapper.selectPathByXzqdm(each_xzqdm));//保存有文件的行政代码以便做标记-自动排重
                String parentid, level2, level3, level4 = null;

                if (each_xzqdm.length() == 2) {
                    continue;
                } else if (each_xzqdm.length() == 4) {//市
                    parentid = each_xzqdm.substring(0, 2);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                } else if (each_xzqdm.length() == 6) {//县
                    parentid = each_xzqdm.substring(0, 4);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                    //添加上级市
                    level2 = xzqMapper.selectXzqmcByXzqdm(parentid);

                    xzqMenu.add(new Xzq(parentid, level2, "44"));
                } else if (each_xzqdm.length() == 9) {//乡
                    parentid = each_xzqdm.substring(0, 6);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                    //添加上级市、县
                    level3 = xzqMapper.selectXzqmcByXzqdm(parentid);
                    level2 = xzqMapper.selectXzqmcByXzqdm(each_xzqdm.substring(0, 4));

                    xzqMenu.add(new Xzq(parentid, level3, each_xzqdm.substring(0, 4)));
                    xzqMenu.add(new Xzq(each_xzqdm.substring(0, 4), level2, "44"));
                } else if (each_xzqdm.length() == 12) {//村
                    parentid = each_xzqdm.substring(0, 9);
                    xzq.setParentid(parentid);
                    xzqMenu.add(xzq);
                    //添加上级市、县、乡
                    level4 = xzqMapper.selectXzqmcByXzqdm(parentid);
                    level3 = xzqMapper.selectXzqmcByXzqdm(each_xzqdm.substring(0, 6));
                    level2 = xzqMapper.selectXzqmcByXzqdm(each_xzqdm.substring(0, 4));

                    xzqMenu.add(new Xzq(parentid, level4, each_xzqdm.substring(0, 6)));
                    xzqMenu.add(new Xzq(each_xzqdm.substring(0, 6), level3, each_xzqdm.substring(0, 4)));
                    xzqMenu.add(new Xzq(each_xzqdm.substring(0, 4), level2, "44"));
                }
            }//end everyYearFileDeal

            List<Xzq> list = new LinkedList<>(xzqMenu);
            yearForFiles.put(ob.getYear(), xzqMenuUtil.menuList(list, xzqdms));
        }//endVO
        return ServerResponse.createBySuccess(yearForFiles);
    }

    /**
     * 上传文件前检查文件是否存在
     *
     * @param xzqdm
     * @param year
     * @return
     */
    @Override
    public int checkFileExist(String xzqdm, String year) {
        if (fileRecordMapper.selectExistByXzqdmAndYear(xzqdm, year) > 0)
            return 1;
        else
            return 0;
    }

    /**
     * 文件下载
     *
     * @param xzqdm
     * @return
     */
    @Override
    public String dowloadFile(String xzqdm) {
        return fileRecordMapper.selectFileNameByXzqdm(xzqdm);
    }

}
